<template>
  <div>
    <el-upload
      v-show="!showPercent"
      action="#"
      :file-list="fileList"
      :on-preview="onPreview"
      :on-remove="onRemove"
      list-type="picture-card"
      :http-request="onRequest"
      :limit="limit"
      :on-exceed="onExceed"
      accept="image/gif, image/jpeg, image/png"
      :before-upload="beforeUpload"
      :on-change="onChange"
      :class="{disabled: fileComputed }"
    >
      <i class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <el-dialog
      title="预览"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <img :src="imgUrl" style="width: 100%">
    </el-dialog>
    <el-progress v-if="showPercent" type="circle" :percentage="percent" />
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDe7JGwMVO0LQEm57sMZWCcldDWZLq41h6',
  SecretKey: '80buwhBOKyMTMyJN9espUxDF3dy5xgAO'
})
export default {
  name: 'UploadImage',
  props: {
    limit: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      dialogVisible: false,
      imgUrl: '',
      fileList: [],
      showPercent: false,
      percent: 0
    }
  },
  computed: {
    // 设定一个计算属性 判断是否已经上传完了一张
    fileComputed() {
      if (this.limit) {
        return this.fileList.length === this.limit
      } else {
        return false
      }
    }
  },
  methods: {
    onRequest({ file }) {
      this.showPercent = true
      const id = setInterval(() => {
        if (this.percent < 90) {
          this.percent++
        } else {
          clearInterval(id)
        }
      }, 500)
      cos.putObject({
        Bucket: 'hrsaas-1308960734', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-shanghai', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        StorageClass: 'STANDARD',
        Body: file, // 上传文件对象
        onProgress: (params) => {
          if (params.percent === 1) {
            this.percent = 100
            clearInterval(id)
            setTimeout(() => {
              this.showPercent = false
              this.percent = 0
            }, 800)
          }
        }
      }, (err, data) => {
        if (err) {
          this.showPercent = false
          this.$message.error('网络错误')
          this.fileList.splice(this.fileList.length - 1, 1)
        }
        if (!err & data.statusCode === 200) {
          this.$message.success('上传成功')
          this.fileList[this.fileList.length - 1].url = 'https://' + data.Location
          this.$emit('on-success', this.fileList)
        }
      })
    },
    // 图片上传本地成功或者失败
    onChange(file, fileList) {
      this.fileList = fileList
    },
    // 点击预览
    onPreview(file) {
      this.imgUrl = file.url
      this.dialogVisible = true
    },
    // 点击删除
    onRemove(file, fileList) {
      this.fileList = fileList
    },
    // 图片上传之前
    beforeUpload(file) {
      const maxSize = 2 * 1024 * 1024
      const fileType = ['image/gif', 'image/jpeg', 'image/png']
      if (!fileType.includes(file.type)) {
        this.$message.error('请上传正确格式的图片')
        return false
      }
      if (file.size > maxSize) {
        this.$message.error('请选择2Mb大小以内的图片')
        return false
      }
    },
    onExceed() {
      this.$message.error(`最多上传${this.limit}张图片`)
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
}

.disabled .el-upload--picture-card {
  display: none
}
</style>
